import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from '../../../../services-common/common.service';
import { SellPromotionManageService } from '../sell-promotion-manage.service';
import { PermissionService } from 'src/app/service/permission.service';

@Component({
  selector: 'app-direct-descent-record',
  templateUrl: './direct-descent-record.component.html',
  styleUrls: ['./direct-descent-record.component.scss'],
  providers: [DatePipe]
})
export class DirectDescentRecordComponent implements OnInit {
  @ViewChild('myFollowup') followupModel: any;

  // seachParams
  seachParams: any = {
    userId: '', // 用户id
    activity: '', // 直降活动
    orderBeginTime: '', // 下单开始时间
    orderEndTime: '', // 下单开始时间
    status: '' // 订单状态：0-有效、1-无效、2-待付款、3-待审核、4-审核不通过、5-审核通过、6-排队发货、7-待发货、8-待收货（已发货）、9-交易完成、10-支付超时、11-客服取消、12-客户取消、13-售后中、14-全部退货
  };
  // 下单时间
  placeOrderTimes: any = [];
  // 订单状态
  orderStateOptions: any = {
    0: '有效',
    1: '无效',
    2: '待付款',
    3: '待审核',
    4: '审核不通过',
    5: '审核通过',
    6: '排队发货',
    7: '待发货',
    8: '待收货(已发货)',
    9: '交易完成',
    10: '支付超时',
    11: '客服取消',
    12: '客户取消',
    13: '售后中',
    14: '全部退货'
  };
  // 已选顶顶那状态
  orderStateSelecteds: any = [];

  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  // 表格data
  tableData: any = [];

  // model
  oddNumber: any = ''; // 关联信息(订单号 售后单号 客户id 出库单号)

  constructor(
    private datePipe: DatePipe,
    private services: SellPromotionManageService,
    private message: NzMessageService,
    private modal: NzModalService,
    private commonService: CommonService,
    public permission: PermissionService
  ) { }

  ngOnInit(): void {
    this.loadTable();
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        page: this.tableForms.page,
        pageSize: this.tableForms.pageSize
      }

      this.tableForms.tableLoading = true;
      const res: any = await this.services.queryPromotionRecordData(params);
      this.tableForms.tableLoading = false;
      if (res.code == 0) {
        const { records, total }: any = res.data || {};
        this.tableData = records || [];
        this.tableForms.total = total || 0;
      } else {
        this.message.error(res.message || '数据获取失败');
      }
    } catch (error: any) {
      this.tableForms.tableLoading = false;
      this.message.error(error);
      this.tableData = [];
      this.tableForms.total = 0;
    }
  }

  // seach date change
  onDateChange(result: Date[]) {
    this.seachParams.orderBeginTime = result.length ? this.datePipe.transform(new Date(result[0]), 'yyyy-MM-dd') : '';
    this.seachParams.orderEndTime = result.length ? this.datePipe.transform(new Date(result[1]), 'yyyy-MM-dd') : '';
  }

  // 订单状态change
  orderStateChange(result: any) {
    this.seachParams.status = result.join(',');
  }

  // 查询
  queryData() {
    this.tableForms.page = 1;
    this.loadTable();
  }
  // 重置
  resetData() {
    for (let key in this.seachParams) {
      this.seachParams[key] = '';
    }

    this.placeOrderTimes = [];
    this.orderStateSelecteds = [];
    this.tableForms.page = 1;
    this.loadTable();
  }

  // open model
  openModel(item: any) {
    this.oddNumber = item.orderNum;
    this.followupModel.showModal();
  }
  // submit
  submitData(data: any) {
    // console.log(data);
    this.loadTable();
  }

  // 取消订单
  cannlOrder(item: any) {
    this.modal.confirm({
      nzTitle: '取消订单',
      nzContent: '<b style="color: red;">确认取消？该操作不可逆，请提前和用户沟通</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        try {
          this.message.loading('loading...', {nzDuration: 0});
          const res: any = await this.services.cancelOrderData({ orderId: item.orderId });
          this.message.remove();
          if (res.code == 0) {
            this.message.success('订单取消成功');
            this.loadTable();
          } else {
            this.message.error(res.message || '订单取消失败');
          }
        } catch (error: any) {
          this.message.remove();
          this.message.error(error);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }

  /**
   * Export Table
   * ----------------------------------------------------------------
   */
  exportTable(type: number) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.seachParams
        }
        const res: any = type === 1 ? (await this.services.exportPromotionMainData(params)) : (await this.services.exportPromotionDetailedData(params));
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '配件直降记录' + (type === 1 ? '主信息' : '明细信息'));
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }
}
